// pages/editAddress/editAddress.js

const app = getApp();
import api from '../../utils/util.js';
const citys = {
  浙江: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
  福建: ['福州', '厦门', '莆田', '三明', '泉州'],
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: true,
    show: false,
    id: null,
    name: '刘德华',
    phone: '',
    location: '',
    isMoren: false,

    columns: [{
        values: Object.keys(citys),
        className: 'column1',
      },
      {
        values: citys['浙江'],
        className: 'column2',
        defaultIndex: 2,
      },
    ],
  },

  async saveAddress() {

    if (this.data.name.trim() === '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return;
    }
    if (this.data.phone.trim() === '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return;
    }
    if (this.data.location.trim() === '') {
      wx.showToast({
        title: '请输入收货地址',
        icon: 'none'
      })
      return;
    }
    const address = {
      id: this.data.id,
      name: this.data.name,
      phone: this.data.phone,
      location: this.data.location,
      isMoren: this.data.isMoren,
      userId: app.globalData.userId
    }
    const index = app.globalData.address.findIndex(e => e.id === address.id)
    app.globalData.address[index] = address;
    const result = await api.post('/address/saveOrUpdate', address);
    wx.navigateBack({
      delta: -1,
    })
  },


  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    picker.setColumnValues(1, citys[value[0]]);
  },

  switch ({
    detail
  }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      isMoren: detail
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.index) {
      const index = options.index;
      this.setData({
        id: app.globalData.address[index].id,
        name: app.globalData.address[index].name,
        location: app.globalData.address[index].location,
        phone: app.globalData.address[index].phone,
        isMoren: app.globalData.address[index].isMoren,
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})